import React, { useState, useEffect } from 'react';
import { Form, Button, Input, Select, Table, Modal, message, TableColumnsType } from 'antd';
import styles from './Gride.module.css';
import axios from 'axios';
interface dataItem {
  id: number;
  title: string;
  money: string;
  children?: dataItem[];
}

interface TreeItem {
  id: number;
  title: string;
  money: string;
  children?: dataItem[];
}

interface AppendForm {
  pid: number;
  title: string;
  money: string;
  safe: string;
  station: string;
  between: string;
  performance: string;
  id?: number; // 新增可选字段
}

const AddRules = {
  title: [{ required: true, message: '请输入档级名称' }],
  mooney: [{ required: true, message: '请输入岗位工资' }],
  safe: [{ required: true, message: '请输入安全质量奖' }],
  station: [{ required: true, message: '请输入岗位津贴' }],
  between: [{ required: true, message: '请输入档级薪资区间' }],
  performance: [{ required: true, message: '请输入绩效薪资' }],
};

export default function gride() {
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]); // 默认展开id=1的行
  // 获取到分页的数据
  const [data, setdata] = useState<dataItem[]>([]);
  const [pageData, setPageData] = useState<dataItem[]>([]);
  const [treeData, setTreeData] = useState<dataItem[]>([]);
  // 添加弹窗
  const [open, setOpen] = useState(false);
  // 添加弹窗表单声明
  const [append] = Form.useForm<AppendForm>();
  // 编辑状态
  const [editState, setEditState] = useState(false);
  const [editData, setEditData] = useState<dataItem>();
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.post('/grade/index/index');
        console.log(response.data);
        setdata(response.data.list);
        setPageData(response.data.list);
        setTreeData(buildTreeEnhanced(response.data.list));
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    fetchData();
  }, []);

  // 声明当前页
  const [currentPage, setCurrentPage] = useState(1);
  // 声明当前页数量
  const [pageSize, setPageSize] = useState(10);
  // 计算分页后的数据
  const paginatedData = treeData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  // 处理分页变化
  const handlePageChange = (page: any, size: any) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 构建二级树结构
  const buildTreeEnhanced = (
    data: Array<{ id: number; pid: number; title: string }>,
    handleOrphans: boolean = false,
  ): any => {
    if (!Array.isArray(data) || data.length === 0) {
      return []; // 如果数据为空，直接返回空数组
    }
    const nodeMap: { [key: number]: any } = {};
    const tree: any[] = [];
    const orphanNodes: any[] = [];
    // 单次遍历构建树结构
    data.forEach((item) => {
      // 初始化节点
      if (!nodeMap[item.id]) {
        nodeMap[item.id] = {
          value: item.id, // 必须字段
          label: item.title, // 必须字段
          ...item, // 保留原始数据
          children: [], // 初始化子节点
        };
      }
      const parentNode = nodeMap[item.pid];
      if (item.pid === 0) {
        tree.push(nodeMap[item.id]); // 根节点
      } else if (parentNode) {
        parentNode.children.push(nodeMap[item.id]); // 子节点
      } else {
        orphanNodes.push(nodeMap[item.id]); // 孤儿节点
      }
    });
    return tree;
  };

  const columns: TableColumnsType<TreeItem> = [
    {
      title: '档级名称',
      dataIndex: 'title',
      key: 'id',
      align: 'center',
    },
    {
      title: '岗位薪资',
      dataIndex: 'money',
      key: 'id',
      align: 'center',
    },
    {
      title: '安全质量奖',
      dataIndex: 'safe',
      key: 'id',
      align: 'center',
    },
    {
      title: '岗位津贴',
      dataIndex: 'station',
      key: 'id',
      align: 'center',
    },
    {
      title: '薪资区间',
      dataIndex: 'between',
      key: 'id',
      align: 'center',
    },
    {
      title: '绩效薪资',
      dataIndex: 'performance',
      key: 'id',
      align: 'center',
    },
    {
      title: '操作',
      key: 'id',
      align: 'center',
      render: (_, record) => (
        <div>
          <Button
            style={{ backgroundColor: '#409EFF', color: 'white', marginRight: '10px' }}
            color="red"
            variant="solid"
            onClick={() => editShow(record)}
          >
            编辑
          </Button>
          <Button
            style={{ backgroundColor: '#F56C6C', color: 'white' }}
            color="red"
            variant="solid"
            onClick={() => showdelete(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];
  // 添加弹窗
  const showModal = () => {
    setOpen(true);
  };
  // 隐藏弹窗
  const hideModal = () => {
    setOpen(false);
    setEditState(false);
    append.resetFields();
  };
  // 添加确认
  const affirm = async () => {
    if (!editState) {
      try {
        const appendfromValue = append.getFieldsValue();
        appendfromValue.pid == undefined
          ? (appendfromValue.pid = 0)
          : (appendfromValue.pid = appendfromValue.pid);
        console.log(appendfromValue);
        const response = await axios.post('/grade/index/add', appendfromValue);
        if (response.data.code) {
          message.success('添加成功');
          setOpen(false);
        }
      } catch (err) {
        console.error('请求失败:', err);
      }
    } else {
      if (editData) {
        try {
          const appendfromValue = append.getFieldsValue();
          appendfromValue.pid = appendfromValue.pid ?? 0;
          appendfromValue.id = editData.id; // 安全访问 id

          const response = await axios.post('/grade/index/edit', appendfromValue);
          if (response.data.code) {
            message.success('编辑成功');
            setOpen(false);
          }
        } catch (err) {
          console.error('请求失败:', err);
        }
      } else {
        message.warning('编辑数据异常，请刷新后重试');
      }
    }
  };
  // 编辑回显
  const editShow = (Item: any) => {
    setOpen(true);
    setEditState(true);
    setEditData(Item);
    append.setFieldsValue({
      pid: Item.pid == 0 ? '0' : Item.pid,
      title: Item.title,
      money: Item.money,
      safe: Item.safe,
      station: Item.station,
      between: Item.between,
      performance: Item.performance,
    });
  };

  const [deleteState, setDeleteState] = useState(false);
  const [deleteId, setdeleteId] = useState();

  const showdelete = (item: any) => {
    setDeleteState(true);
    setdeleteId(item);
  };

  const hidedelete = () => {
    setDeleteState(false);
  };

  const Confirm = async () => {
    try {
      const response = await axios.post('/grade/index/del', { id: deleteId });
      if (response.data.code == 2) {
        message.success('删除成功');
        setDeleteState(false);
      }
    } catch (err) {
      console.error('请求失败:', err);
    }
  };

  return (
    <div>
      <Button
        style={{ backgroundColor: '#0052CC', color: 'white', marginLeft: '15px' }}
        color="red"
        variant="solid"
        onClick={showModal}
      >
        新增
      </Button>
      <Table<TreeItem>
        style={{ marginTop: '30px' }}
        bordered={true}
        columns={columns}
        rowKey="id"
        dataSource={treeData}
        expandable={{
          childrenColumnName: 'children',
          expandedRowKeys,
          onExpand: (expanded, record) => {
            const keys = expanded
              ? [...expandedRowKeys, record.id]
              : expandedRowKeys.filter((key) => key !== record.id);
            setExpandedRowKeys(keys);
          },
        }}
        pagination={{
          position: ['bottomCenter'], // 控制位置
          style: {
            marginTop: 16,
            textAlign: 'center',
            justifyContent: 'center',
          },
        }}
      />
      <Modal
        title="添加档级"
        open={open}
        width={850}
        onOk={affirm}
        onCancel={hideModal}
        okText="确认"
        cancelText="取消"
      >
        <Form form={append}>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="pid"
            layout="horizontal"
            label="项目所属公司"
          >
            <Select
              disabled={editState}
              placeholder="请选择项目所属公司"
              allowClear
              options={treeData.map((item) => ({
                value: item.id,
                label: item.title,
              }))}
            />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="title"
            layout="horizontal"
            label="档级名称"
            rules={AddRules.title}
          >
            <Input placeholder="请输入档级名称" />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="money"
            layout="horizontal"
            label="岗位工资"
            rules={AddRules.mooney}
          >
            <Input placeholder="请输入岗位工资" type="number" />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="safe"
            layout="horizontal"
            label="安全质量奖"
            rules={AddRules.safe}
          >
            <Input placeholder="请输入安全质量奖" type="number" />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="station"
            layout="horizontal"
            label="档级名称"
            rules={AddRules.station}
          >
            <Input placeholder="请输入岗位津贴" type="number" />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="between"
            layout="horizontal"
            label="档级薪资区间"
            rules={AddRules.between}
          >
            <Input placeholder="请输入档级薪资区间" type="number" />
          </Form.Item>
          <Form.Item<AppendForm>
            labelCol={{ span: 3 }}
            className={styles.formItem}
            name="performance"
            layout="horizontal"
            label="绩效薪资"
            rules={AddRules.performance}
          >
            <Input placeholder="请输入绩效薪资" type="number" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="删除"
        open={deleteState}
        onOk={Confirm}
        centered
        onCancel={hidedelete}
        okText="确认"
        cancelText="取消"
      >
        <div className={styles.deleteBox}>
          <img className={styles.delete} src={require('@/img/warn.png')} alt="" />
          确定要删除当前档级吗?
        </div>
      </Modal>
    </div>
  );
}
